<?php

/**
 * Created by PhpStori.
 * User: Administrator
 * Date: 2017/6/5
 */

namespace app\information\controller;

use app\classes\model\ClassModel;
use app\educational\model\MessageModel;
use app\information\model\InformationModel;
use app\system\model\SchoolModel;
use app\user\model\UserModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Log;

class InformationController extends AdminBaseController
{
    /*
     * 待办信息列表
     */
    public function index()
    {
        $param = $this->request->param();
        $limit = config('limit_per_page');
        $super_admin = 0;//标记非超级管理员
        $where = [];
        //店铺ID
        $where['i.shop_id'] = ['=', $this->admin_shop_id];

        //TODO:权限限制
        $uid = cmf_get_current_admin_id();//当前用户id
        $class_mdl = new ClassModel();
        $roles = $class_mdl->roleAuth($uid, $this->admin_shop_id);
        if (count($roles) > 0) {
            foreach ($roles as $v) {
                if ($v['name'] == '超级管理员') {
                    $super_admin = 1;
                    break;
                }
            }
        }
        if($super_admin == 0){
            //非管理员
            $where['i.solved_uid'] = ['=', $uid];
        }

        if (!empty($param['keywords'])) {
            $where['i.title|i.content'] = ['like', '%' . trim($param['keywords']) . '%'];
        }

        if (!empty($param['school_id']) && intval($param['school_id']) != 0) {
            //校区
            $where['i.school_id'] = ['=', intval($param['school_id'])];
        }

        if (isset($param['status']) && intval($param['status']) != -1) {
            //状态
            $where['i.status'] = ['=', intval($param['status'])];
        }

        if(!empty($param['start']) && !empty($param['end'])) {
            //完成时间
            $start = strtotime($param['start']);
            $end = strtotime('+23 hours 59 minutes 59 seconds', strtotime($param['end']));
            $where['i.solved_time'] = [['>= time', $start], ['<= time', $end]];
        } else {
            if (!empty($param['start'])) {
                $where['i.solved_time'] = ['>= time', strtotime($param['start'])];
            }
            if (!empty($param['end'])) {
                $end = strtotime('+23 hours 59 minutes 59 seconds', strtotime($param['end']));
                $where['i.solved_time'] = ['<= time', $end];
            }
        }

        //分页url额外参数
        $page_query = [
            'keywords' => isset($param['keywords']) ? $param['keywords'] : '',
            'school_id' => isset($param['school_id']) ? $param['school_id'] : '',
            'status' => isset($param['status']) ? $param['status'] : '-1',
            'start' => isset($param['start']) ? $param['start'] : '',
            'end' => isset($param['end']) ? $param['end'] : '',
        ];

        //排序
        $sort = [];

        $info_mdl = new InformationModel();
        $data = $info_mdl->getInfo($where, $sort, $limit, $page_query);

        //获取校区
        $school_mdl = new SchoolModel();
        $campus = $school_mdl->getAllSchool($this->admin_shop_id);

        $this->assign('campus', $campus);
        $this->assign('param', $param);
        $this->assign('info', $data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /**
     * 模糊搜索用户(Ajax自动补全功能)
     * @return \think\response\Json
     */
    public function ajax_user()
    {
        $data = [
            '没有匹配的结果'
        ];

        $param = $this->request->param();
        if(empty($param['query'])){
            $json_data = [
                'query' => 'Unit',
                'suggestions' => $data
            ];
            return json($json_data);
        }

        //获取班级
        $where = [
            'u.shop_id' => ['eq', $this->admin_shop_id],
            'u.user_type' => ['eq', 1],//管理员
            'u.user_status' => ['eq', 1],//正常启用
            'u.pinyin|u.short_pinyin|u.realname' => ['like','%'.trim($param['query']).'%'],
        ];

        //获取管理员
        $user_mdl = new UserModel();
        $result = $user_mdl->alias('u')->field('u.id as data,u.realname as value')
            ->where($where)
            ->order('u.id','asc')
            ->select();
        if(count($result) > 0){
            $data = $result;
        }

        $json_data = [
            'query' => 'Unit',
            'suggestions' => $data
        ];
        return json($json_data);
    }

    /*
     * 添加信息
     */
    public function add()
    {
        //获取校区
        $school_mdl = new SchoolModel();
        $campus = $school_mdl->getAllSchool($this->admin_shop_id);

        $this->assign('campus', $campus);
        return $this->fetch();
    }

    //信息模板生成
    public function addPost()
    {
        $cur_time = time();
        $validate = validate('Information');
        if ($this->request->isPost()) {
            $data = $this->request->except('solve');

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            if(empty(trim($data['title'])) || empty(trim($data['content']))){
                $this->error('标题和内容都不能为空');
            }

            $info_mdl = new InformationModel();

            $cur_admin_id = cmf_get_current_admin_id();
            $total = $info_mdl->where('shop_id', '=', $this->admin_shop_id)
                ->where('delete_time', '=', 0)
                ->where('uid', '=', $cur_admin_id)
                ->where(['school_id' => $data['school_id']])
                ->where(['title' => trim($data['title'])])
                ->where(['content' => trim($data['content'])])
                ->count();
            if (isset($total) && $total >= 1) {
                $this->error('该信息已存在');
            }

            $data['uid'] = $cur_admin_id;
            $data['create_time'] = $cur_time;

            $id = $info_mdl->allowField(true)->insertGetId($data);
            $pk = $id; //主键
            $table = 'information';//数据表名
            if ($id) {
                //记录日志
                $content = lang('ADD_BACKLOG', ['name' => $data['title']]);
                do_log($content, $pk, $table, $cur_time);

                //发送通知
                $user_name = Db::name("user")->where('id', $data['solved_uid'])->value('user_login');
                $info_url = url('information/edit',['id'=>$id]);
                $content = lang('ADD_INFO_FINISHER', ['name'=>$user_name, 'infoUrl'=>$info_url]);

                $msg_data['shop_id'] = $this->admin_shop_id;
                $msg_data['type'] = 0;
                $msg_data['subject'] = '前台待办';
                $msg_data['content'] = $content;
                $msg_data['send_uid'] = cmf_get_current_admin_id();
                $msg_data['create_time'] = time();
                $ids[] = ['id' => $data['solved_uid']];

                $msg_mdl = new MessageModel();
                $msg_mdl->sendMsg($msg_data, $ids);

                $this->success('添加成功', 'information/index', '', 2);
            } else {
                $this->error("添加失败");
            }
        }
    }


    /**
     * 编辑信息
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        if (empty($id)) {
            $this->error('参数为空');
        }

        $super_admin = 0;//标记非超级管理员
        //TODO:权限限制
        $uid = cmf_get_current_admin_id();//当前用户id
        $class_mdl = new ClassModel();
        $roles = $class_mdl->roleAuth($uid, $this->admin_shop_id);
        if (count($roles) > 0) {
            foreach ($roles as $v) {
                if ($v['name'] == '超级管理员') {
                    $super_admin = 1;
                    break;
                }
            }
        }

        $info_mdl = new InformationModel();
        $data = $info_mdl->alias('i')->field('i.*,sc.name as campus_name,u.user_login as u_name,
        (SELECT us.user_login FROM cmf_user us WHERE i.solved_uid=us.id) AS solved_name')
            ->join('school sc','i.school_id=sc.id')
            ->join('user u','i.uid=u.id')
            ->where('i.id', $id)
            ->where('i.delete_time', 'eq',0)
            ->find();
        if (empty($data->id)) {
            $this->error('没有该信息或已被删除');
        }

        //获取校区
        $school_mdl = new SchoolModel();
        $campus = $school_mdl->getAllSchool($this->admin_shop_id);

        $this->assign('super_admin', $super_admin);
        $this->assign('campus', $campus);
        $this->assign('data', $data);
        return $this->fetch();

    }

    /*
     * 保存编辑信息
     */
    public function editPost()
    {
        $cur_time = time();
        $validate = validate('Information');
        if ($this->request->isPost()) {
            $data = $this->request->except('solve');

            $id = $data['id'];
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            $cur_admin_id = cmf_get_current_admin_id();
            $info_mdl = new InformationModel();
            $filter_id = [
                'id' => ['eq', intval($id)],
                'shop_id' => ['eq', $this->admin_shop_id]
            ];
            $result = $info_mdl->getInfoByField($filter_id);
            if (isset($result->id) && empty($result->id)) {
                $this->error('没有该信息', 'information/index');
            }

            $filter = [
                'school_id' => ['eq', $data['school_id']],
                'title' => ['eq', trim($data['title'])],
                'content' => ['eq', trim($data['content'])],
                'uid' => ['eq', $cur_admin_id],
                'shop_id' => ['eq', $this->admin_shop_id]
            ];
            $res = $info_mdl->getInfoByField($filter);
            if (isset($res->id) && ($res->id != $id)) {
                $this->error('该信息已存在');
            }

            $data['uid'] = $cur_admin_id;
            $data['update_time'] = $cur_time;

            if(isset($data['status']) && $data['status']==1){
                //标记已处理
                $data['solved_time'] = $cur_time;
            }else{
                //待办
                $data['solved_time'] = 0;
            }

            $res = $info_mdl->editInfo($data);
            $pk = $id; //主键
            $table = 'information';//数据表名
            if ($res) {
                if(isset($data['status']) && $data['status']==0){
                    //待办就发送通知
                    $user_name = Db::name("user")->where('id', $data['solved_uid'])->value('user_login');
                    $info_url = url('information/edit',['id'=>$id]);
                    $content = lang('ADD_INFO_FINISHER', ['name'=>$user_name, 'infoUrl'=>$info_url]);

                    $msg_data['shop_id'] = $this->admin_shop_id;
                    $msg_data['type'] = 0;
                    $msg_data['subject'] = '前台待办';
                    $msg_data['content'] = $content;
                    $msg_data['send_uid'] = cmf_get_current_admin_id();
                    $msg_data['create_time'] = time();
                    $ids[] = ['id' => $data['solved_uid']];

                    $msg_mdl = new MessageModel();
                    $msg_mdl->sendMsg($msg_data, $ids);
                }

                //记录日志
                $content = lang('EDIT_BACKLOG', ['name' => $data['title']]);
                do_log($content, $pk, $table, $cur_time);

                $this->success('编辑成功', 'information/index', '', 2);
            } else {
                $this->error("编辑失败");
            }
        }
    }

    /*
     * 删除
     */
    public function delete()
    {
        $cur_time = time();
        $table = 'information,recycleBin';
        $info_mdl = new InformationModel();

        $param = $this->request->param();
        if (isset($param['id'])) {
            $id = $this->request->param('id', 0, 'intval');
            $data = Db::name('information')->where('id', $id)->find();
            //记录日志
            $pk = $id;
            $content = lang('DELETE_BACKLOG', ['name' => $data['title']]);

        } else {
            $id = $this->request->param('ids/a');
            //记录日志
            $pk = implode(',', $id);
            $content = lang('BATCH_DELETE', ['name' => '前台待办信息']);
        }

        $result = $info_mdl->deleteInfo($id, $cur_time);
        if ($result) {
            do_log($content, $pk, $table, $cur_time);

            $this->success("删除成功！", '');
        } else {
            $this->error('删除失败！');
        }
    }


}